package org.black.phoneUtility.sms.schedule.content.broadcastReceiver;

import org.black.phoneUtility.sms.schedule.SmsScheduleConstant;
import org.black.phoneUtility.sms.schedule.provider.SmsScheduleContract;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.SmsManager;
import android.util.Log;

public class SentSmsBroadcastReceiver extends BroadcastReceiver {

	public static final String ARGUMENTS_SENDING_RECORD_ID = "arguments_sending_record_id";
	public static final String ARGUMENTS_DESTINATION_ADDRESS = "arguments_destination_address";

	private static final String LOG_TAG = SentSmsBroadcastReceiver.class
			.getName();

	@Override
	public void onReceive(Context context, Intent intent) {
		if (SmsScheduleConstant.SMS_SENT_INTENT.equals(intent.getAction())) {
			int resultCode = getResultCode();
			Log.d(LOG_TAG, "result code : " + resultCode);
			Uri data = intent.getData();
			WriteReplyHistoryThread writeReplyHistoryThread = new WriteReplyHistoryThread(
					context, data, resultCode);
			writeReplyHistoryThread.start();
			switch (resultCode) {
			case Activity.RESULT_OK: {
				Log.d(LOG_TAG, "Send Success.");
				break;
			}
			case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
				Log.d(LOG_TAG, "Generic Fail!");
				break;
			case SmsManager.RESULT_ERROR_NO_SERVICE:
				Log.d(LOG_TAG, "No SMS Service");
				break;
			case SmsManager.RESULT_ERROR_NULL_PDU:
				Log.d(LOG_TAG, "PDU Error!");
				break;
			case SmsManager.RESULT_ERROR_RADIO_OFF:
				Log.d(LOG_TAG, "Radio Off!");
				break;
			}
		}

	}

	private class WriteReplyHistoryThread extends Thread {
		private Context context;
		private Uri uri;
		private int sendingStatus;

		public WriteReplyHistoryThread(Context context, Uri uri,
				int sendingStatus) {
			this.context = context;
			this.uri = uri;
			this.sendingStatus = sendingStatus;
		}

		@Override
		public void run() {
			if (uri != null) {
				ContentValues scheduleSendingRecordRecipientContentValues = new ContentValues();
				scheduleSendingRecordRecipientContentValues
						.put(SmsScheduleContract.SmsScheduleSendingRecordRecipients.SENDING_STATUS,
								sendingStatus);
				context.getContentResolver()
						.update(uri,
								scheduleSendingRecordRecipientContentValues,
								null, null);
			}

		}
	}

}
